<%@ page contentType="application/json;charset=UTF-8" language="java" %><%--
--%><%@ page import="spacecrack.Player" %><%--
--%><%@ page import="spacecrack.PlayerManager" %><%--
--%><%@ page import="spacecrack.NameRandomizer" %><%--
--%><%@ page import="java.util.List" %><%--
--%><%@ page import="com.google.appengine.api.users.User" %><%--
--%><%@ page import="com.google.appengine.api.users.UserService" %><%--
--%><%@ page import="com.google.appengine.api.users.UserServiceFactory" %><%--
--%><%@ page import="o.json.JSONFactory" %><%--
--%><%@ page import="o.json.JSONWriter" %><%--
--%><%

	class Response {
		private String status;
		private Player player;

		public Response() {}
		public Response(String status, Player player) {
			this.status = status;
			this.player = player;
		}

		public String getStatus() { return status; }
		public void setStatus(String status) { this.status = status; }
		public Player getPlayer() { return player; }
		public void setPlayer(Player player) { this.player = player; }
	}
	final Response resp = new Response();

	final UserService us = UserServiceFactory.getUserService();
	final PlayerManager pm = new PlayerManager();

	if (us.isUserLoggedIn()) {

		final User user = us.getCurrentUser();
		final String id = user.getEmail();
		final Player player;
		if (pm.playerExists(id)) {
			player = pm.loadPlayerById(id);
		} else {
			final String name = NameRandomizer.get(10);
			player = new Player(id, name);
			pm.storePlayer(player);
		}
		resp.setPlayer(player);

		final JSONWriter writer = new JSONWriter();
		final JSONFactory f = new JSONFactory();
//		writer.write(f.create(resp));
		writer.write(f.create(player));

%><%= writer.toString() %><%

	} else {

		System.out.println("user is not logged on!");
//		writer.write(f.create(us.createLoginURL("logon")));
//		resp.setStatus("login");
		response.sendError(401);

	}

%>